package cc.vicp.djx314.starfood.web.user;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.support.ServletContextResource;

import cc.vicp.djx314.starfood.domain.account.User;
import cc.vicp.djx314.starfood.service.account.UserInfoService;
import cc.vicp.djx314.starfood.web.exception.UserNotSameAsSessionException;
import cc.vicp.djx314.starfood.web.exception.UserSessionTimeOutException;

@Controller
public class UserInfoPhotoUpdateController {
	public static final Logger logger = LoggerFactory.getLogger(UserInfoPhotoUpdateController.class);

	@Autowired
	UserInfoService userInfoService;

	@RequestMapping(value = "/user/photoupdate/{id}", method = RequestMethod.GET)
	public String updatePhotoPage(@PathVariable("id") Integer id) {
		return "customer/user/userinfoupdatephoto";
	}

	@RequestMapping(value = "/user/photoupdate/{id}", method = RequestMethod.PUT)
	public String updatePhoto(@PathVariable("id") Integer id,
			@RequestParam("filePath") String filePath, HttpSession session,
			HttpServletRequest request)
					throws UserSessionTimeOutException, UserNotSameAsSessionException {
		User user = (User) session.getAttribute("loginUser");
		if (user == null) {
			throw new UserSessionTimeOutException("用户session过时");
		}
		if (id.equals(user.getId()) == false) {
			throw new UserNotSameAsSessionException("请求的用户id:  " + id +
					"  与session的用户id:  " + user.getId() + "  不符");
		}
		String resultString = null;
		try {
			ServletContext context = request.getSession().getServletContext();
			Resource resource = new ServletContextResource(context, "/img/headtemp/" + filePath);
			File headImgFile = resource.getFile();
			byte[] headImg = FileCopyUtils.copyToByteArray(headImgFile);
			userInfoService.updateUserPhoto(id, headImg);
			resultString = "redirect:/user/info/" + id + "?photoChangeSuccess=true";
		} catch (IOException e1) {
			logger.info("头像文件找不到", e1);
			resultString = "redirect:/user/photoupdate/" + id + "?fileNotFound=true";
		} catch (Exception e2) {
			logger.error("创建用户发生未知错误", e2);
			resultString = "redirect:/user/photoupdate/" + id + "?unkonwnError=true";
		}
		return resultString;
	}
}